
// make sure that windo.requestAnimationFrame is defined
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }
 
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }
    if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function(id) {
        clearTimeout(id);
        };
    }
}());

function randomArrayElement(array){
    if (array.length == 0){
        return undefined;
    }
    var index = Math.floor(Math.random() * array.length);
    return array[index];
}

function Animation(width, height, image, context, animations, period){
    this.img = image
    this.width = width;
    this.height = height;
    this.context = context;
    this.animations = animations;
    this.period = period;
};
Animation.prototype = {
    draw: function(x, y, animation, time){
        var anim = this.animations[animation];
        var row = anim.row || 0;
        var frames = anim.frames || Math.floor(this.img.naturalWidth/this.width);
        var period = anim.period || this.period;
        if (!this.start){
            this.start = time;
        }
        var frame = Math.floor((time - this.start)/period) % frames;
        //console.warn(' %s, %s, %s, %s, %s, %s, %s, %s', frame*this.width, row*this.height, this.width, this.height, x, y, this.width, this.height)
        this.context.drawImage(this.img, frame*this.width, row*this.height, this.width, this.height, x, y, this.width, this.height);
    }
};